<?php

/**
 * TelnetCommand class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Tuesday, October 4, 2011. 11:40 AM
 */
class TelnetCommand extends CConsoleCommand {

	public function getHelp() {
		return <<<EOD
USAGE
    telnet [params]
DESCRIPTION
    This command send telnet command to Chachamaru.
EOD;
	}

	private $_telnet;

	public function run($args) {
		print "Running Haruna Scheduler.\n\n";
		$args = ($_SERVER['argv']);
		if (count($args) < 3) return;

		if (!$this->_connect()) return;

		switch ($args[2]) {
			case 'mood':
				$this->_setMood($args[3]);
				break;
			case 'light':
				$this->_setLight($args[3], $args[4]);
				break;
			default:
				print 'Unknown command.\n';
				break;
		}

		$this->_disconnect();
	}

	private function _setMood($moodId) {
		printf("Activating mood id \"%s\".\n", $moodId);
		$mood = Mood::model()->findByPk($moodId);
		if (!$mood) {
			printf("Mood id \"%s\" is missing.\n", $moodId);
			return;
		}

		foreach ($mood->moodLights as $moodLight) {
			$this->_setLight($moodLight->lightId, $moodLight->value);
		}
	}

	private function _setLight($lightId, $value) {
		printf("Set light id \"%s\" to value \"%s\".\n", $lightId, $value);
		$light = Light::model()->findByPk($lightId);
		if (!$light) {
			printf("Light id \"%s\" is missing.\n", $lightId);
			return;
		}

		$format = "%02d%02d%03d";
		$command = sprintf($format, $light->host, $light->channel, $value);
		$this->_attention($command);
	}

	private function _connect() {
		print 'Connecting to Chachamaru...';
		try {
			$host = '127.0.0.1';
			$this->_telnet = @fsockopen($host, 7777, $number, $message, 30);
			print " OK ^_^\n";
			stream_set_timeout($this->_telnet, 10);
			fgets($this->_telnet, 128);
			return true;
		} catch (Exception $e) {
			print " Error >_<\n";
			return false;
		}
	}

	private function _disconnect() {
		print 'Disconnecting from Chachamaru...';
		if (fclose($this->_telnet)) print " OK ^_^\n";
		else print " Error >_<\n";
	}

	private function _attention($command) {
		printf("Sending command \"%s\" to Chachamaru...", $command);
		if (fwrite($this->_telnet, $command . "\n") === false) {
			print " Error >_<\n";
			return false;
		}
		time_nanosleep(0, 200000);
		print " OK ^_^\n";
		return true;

//		if (($response = fgets($this->_telnet, 128)) === false) {
//			print "Read error\n";
//			return false;
//		}
//
//		return $response;
	}

}
